/*
 *  Copyright 2008-2010 www.jrails.org
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package org.rails.extjs;

import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.rails.extjs.javascript.Script;
import org.rails.extjs.json.Json;

public final class ExtJS {

	public static void bind(HttpServletRequest request, AbsBase base) {
		bind(request,base.getScript());
	}
	
	public static void bind(HttpServletRequest request,Script script) {
		bind(request,script.getScript());
	}
	
	public static void bind(HttpServletRequest request,Json json) {
		bind(request,json.createJson());
	}
	
	@SuppressWarnings("unchecked")
	private static void bind(HttpServletRequest request,String s){
		StringBuffer sum = new StringBuffer();
		Object temp = request.getAttribute("ExtJS");
		Map<String, String> extJS = temp == null ? new HashMap<String, String>()
				: (Map<String, String>) temp;
		sum.append(replaceEmpty(extJS.get("script")));
		sum.append(replaceEmpty(s));
		extJS.put("script", sum.toString());
		request.setAttribute("ExtJS", extJS);
	}

	@SuppressWarnings("unchecked")
	public static String getDebugScript(HttpServletRequest request) {
		if (AbsBase.debug)
			return ((Map<String, String>) request.getAttribute("ExtJS"))
					.get("script");
		else
			return "";
	}

	@SuppressWarnings("unchecked")
	public static String getScript(HttpServletRequest request) {
		return ((Map<String, String>) request.getAttribute("ExtJS"))
				.get("script");
	}

	@SuppressWarnings("unchecked")
	public static void sendToClient(HttpServletRequest request, Writer writer)
			throws IOException {
		Object temp = request.getAttribute("ExtJS");
		Map<String, String> extJS = (temp == null ? new HashMap<String, String>()
				: (Map<String, String>) temp);
		writer.write(replaceEmpty(extJS.get("script")));
	}

	private static String replaceEmpty(Object arg) {
		return arg == null ? "" : arg.toString();
	}

}
